package com.doubao.wechat.controller;

import com.doubao.common.result.Result;
import com.doubao.wechat.dto.request.WxLoginRequest;
import com.doubao.wechat.dto.response.WxUserInfoDTO;
import com.doubao.wechat.service.WechatService;
import com.doubao.wechat.feign.UserFeignClient;
import com.doubao.wechat.feign.dto.UserDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
@RequiredArgsConstructor
@Tag(name = "微信服务", description = "微信相关接口")
@Slf4j
public class WechatController {

    private final UserFeignClient userFeignClient;
    private final WechatService wechatService;

    /**
     * 微信小程序登录
     */
    @PostMapping("/miniapp/login")
    @Operation(summary = "微信小程序登录", description = "获取微信小程序用户信息")
    public Result<WxUserInfoDTO> miniappLogin(@Valid @RequestBody WxLoginRequest request) {
        return wechatService.miniappLogin(request);
    }

    /**
     * 获取微信session key
     */
    @GetMapping("/session-key")
    @Operation(summary = "获取SessionKey", description = "根据code获取微信session_key和openid")
    public Result<Map<String, Object>> getSessionKey(@RequestParam("code") String code) {
        Map<String, Object> sessionMap = wechatService.getSessionKey(code);
        if (sessionMap != null && sessionMap.containsKey("errcode")) {
            return Result.failed("获取session_key失败: " + sessionMap.get("errmsg"));
        }
        return Result.success(sessionMap);
    }

    /**
     * 检查用户是否已绑定微信 - 新增接口
     */
    @GetMapping("/user/check-binding")
    @Operation(summary = "检查微信绑定状态", description = "检查用户是否已绑定微信账号")
    public Result<Map<String, Object>> checkWechatBinding(@RequestParam("userId") Long userId) {
        try {
            // 调用用户服务检查绑定状态
            Result<UserDTO> userResult = userFeignClient.getUserById(userId);

            if (!userResult.isSuccess() || userResult.getData() == null) {
                return Result.failed("用户不存在");
            }

            UserDTO user = userResult.getData();
            // 检查用户是否有微信openid（假设UserDTO中有miniappOpenid字段）
            boolean isBound = StringUtils.isNotBlank(user.getMiniappOpenid());

            Map<String, Object> result = new HashMap<>();
            result.put("isBound", isBound);

            return Result.success(result);
        } catch (Exception e) {
            log.error("检查微信绑定状态失败", e);
            return Result.failed("检查绑定状态失败");
        }
    }

    /**
     * 获取微信openid并关联到已有用户 - 已有接口，重命名为更清晰的名称
     */
    @PostMapping("/user/bind-wechat")
    @Operation(summary = "绑定微信账号", description = "获取微信openid并绑定到已有用户账号")
    public Result<Void> bindWechatToUser(@RequestParam("userId") Long userId,
                                         @RequestParam("code") String code) {
        return wechatService.bindOpenidToUser(userId, code);
    }

    /**
     * 原有的bindOpenidToUser接口保持兼容
     */
    @PostMapping("/bind-openid")
    @Operation(summary = "获取微信openid并关联用户", description = "在下单前获取微信openid并绑定到已有用户账号")
    public Result<Void> bindOpenidToUser(@RequestParam("userId") Long userId,
                                         @RequestParam("code") String code) {
        return wechatService.bindOpenidToUser(userId, code);
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取详细信息")
    public Result<UserDTO> getUserById(@PathVariable("userId") Long userId) {
        log.info("微信模块 - 获取用户信息: userId={}", userId);
        return userFeignClient.getUserById(userId);
    }
}